﻿using Google.Protobuf.WellKnownTypes;

namespace Elio.Sessions;
public class FileSession : BaseSession
{
    private string? _path;
    private string? _fileName;
    protected override string SessionName => base.SessionName = "File";

    protected override async Task OnReceive(string name, long sessionId, long futureId, params Any[] argv)
    {
        switch (name)
        {
            case "open":
                Open(argv);
                break;

            case "read":
                await Read(sessionId, futureId);
                break;

            case "readLine":
                ReadLine();
                break;

            case "write":
                await Write(argv);
                break;

            case "exists":
                await Exists(sessionId, futureId);
                break;

            case "remove":
                Remove();
                break;

            default:
                await base.OnReceive(name, sessionId, futureId, argv);
                break;
        }
    }
    private void Open(params Any[] argv)
    {
        // 在运行目录创建一个 data 文件夹
        string path = Path.Combine(AppContext.BaseDirectory, "data");
        if (!Directory.Exists(path)) Directory.CreateDirectory(path);

        _fileName = argv[0].P2String();
        this._path = Path.Combine(path, _fileName);
    }

    private async Task Read(long sid, long fid)
    {
        string data = string.Empty;
        if (_path is not null && File.Exists(_path))
        {
            data = await File.ReadAllTextAsync(_path);
        }
        await SendAction("onRead", sid, fid, data.ToAny());
    }

    private static void ReadLine() { }

    private async Task Write(params Any[] argv)
    {
        if (_path is not null)
        {
            await File.WriteAllTextAsync(_path, argv[0].P2String());
        }
    }

    private async Task Exists(long sid, long fid) =>
       await SendAction("onExists", sid, fid, File.Exists(_path).ToAny());
    private void Remove()
    {
        if (File.Exists(_path)) File.Delete(_path);
    }
}